<template>
  <div class="pwd_container">
    <el-form class="pwd_form" :model="pwdForm" :rules="pwdRules" ref="pwdForm">
        <!-- 旧密码 -->
        <el-form-item prop="old">
          <el-input placeholder="请输入旧密码" v-model="pwdForm.old" show-password>
            <i slot="prefix" class="el-input__icon el-icon-lock"></i>
          </el-input>
        </el-form-item>
        <!-- 新密码 -->
        <el-form-item prop="new">
          <el-input placeholder="请输入新密码" v-model="pwdForm.new" show-password>
            <i slot="prefix" class="el-input__icon el-icon-lock"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="check">
          <el-input placeholder="请重新输入新密码" v-model="pwdForm.check" show-password>
            <i slot="prefix" class="el-input__icon el-icon-lock"></i>
          </el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="info" @click="resetPwdForm">重置</el-button>
          <el-button type="primary" @click="updatePwd">修改</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import { pwdAPI } from '@/api/userAPI.js'

export default {
  name: 'Password',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pwdForm.new) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      pwdForm: {
        old: '',
        new: '',
        check: ''
      },
      pwdRules: {
        old: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        new: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        check: [
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单
    resetPwdForm () {
      this.$refs.pwdForm.resetFields()
    },
    updatePwd () {
      // validate 对表单输入内容进行验证
      this.$refs.pwdForm.validate(async valid => {
        if (!valid) return
        const params = {
          username: JSON.parse(sessionStorage.getItem('token')).username,
          odl: this.pwdForm.old,
          new: this.pwdForm.new,
          identity: this.identity
        }
        const { data: res } = await pwdAPI(params)
        if (res.status !== 200) {
          this.$message.error(res.data.msg)
          return
        }
        this.$message.success(res.data.msg)
        this.resetPwdForm()
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .pwd_container {
    width: 100%;
    height: 100%;
    position: relative;

    .pwd_form {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 60%;

      .btns {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>>
